MAKEFLAGS = -sR
MKDIR = mkdir
RMDIR = rmdir
CP = cp
CD = cd
DD = dd
RM = rm

ASM		= nasm
CC		= gcc
LD		= ld
OBJCOPY	= objcopy
ASM_FILE = $(shell find . -name "*.asm")
ASM_OBJ_FILE = $(patsubst %.asm, %.o, $(ASM_FILE))
C_FILE = $(shell find . -name "*.c")
C_OBJ_FILE = $(patsubst %.c, %.o, $(C_FILE))

ASMBFLAGS	= -f elf -w-orphan-labels
CFLAGS		= -c -Os -std=c99 -m32 -Wall -Wshadow -W -Wconversion -Wno-sign-conversion  -fno-stack-protector -fomit-frame-pointer -fno-builtin -fno-common  -ffreestanding  -Wno-unused-parameter -Wunused-variable
LDFLAGS		= -s -static -T link.ld -n -Map HelloOS.map 
OJCYFLAGS	= -S -O binary

HELLOOS_OBJS :=
HELLOOS_OBJS += $(ASM_OBJ_FILE)
HELLOOS_OBJS += $(C_OBJ_FILE)
HELLOOS_ELF = HelloOS.elf
HELLOOS_BIN = HelloOS.bin

.PHONY : build clean all link bin copy

all: clean build link bin copy

copy:
	@echo 删除原bin文件
	$(shell rm -f isodir/boot/HelloOS.bin)
	@echo 复制bin文件
	$(shell cp HelloOS.bin isodir/boot)
	@echo 生成启动镜像 myos.iso
	$(shell grub-mkrescue -o myos.iso isodir 2> /dev/null)
clean:
	@echo 清理中间文件
	$(RM) -f *.o *.bin *.elf *.iso *.map isodir/boot/HelloOS.bin

build: $(HELLOOS_OBJS)

link: $(HELLOOS_ELF)
$(HELLOOS_ELF): $(HELLOOS_OBJS)
	@echo 链接目标文件 $(HELLOOS_OBJS)
	$(LD) $(LDFLAGS) -o $@ $(HELLOOS_OBJS)
bin: $(HELLOOS_BIN)
$(HELLOOS_BIN): $(HELLOOS_ELF)
	@echo 从$<提取纯二进制信息到$@
	$(OBJCOPY) $(OJCYFLAGS) $< $@

%.o : %.asm
	@echo 编译汇编代码 $<
	$(ASM) $(ASMBFLAGS) -o $@ $<
%.o : %.c
	@echo 编译C代码 $<
	$(CC) $(CFLAGS) -o $@ $<
qemu:
	qemu-system-i386 -cdrom myos.iso
